import { app, shell, BrowserWindow, ipcMain, session } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'

let mainWindow; // 关键：全局保存窗口实例（用于IPC监听中访问）

function createWindow() {
  // Create the browser window.
  mainWindow = new BrowserWindow({ // 赋值给全局变量
    width: 400,
    height: 550,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    }
  })

  // 设置请求代理（如需启用，取消注释）
  // setupProxy(mainWindow)

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url)
    return { action: 'deny' }
  })

  // HMR for renderer base on electron-vite cli.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
}

// 代理设置函数（保持不变）
function setupProxy(mainWindow) {
  mainWindow.webContents.session.webRequest.onBeforeRequest((details, callback) => {
    if (details.url.includes('/api/')) {
      const targetUrl = details.url.replace(/.*?\/api/, 'http://cc:8000')
      console.log(`Proxying request: ${details.url} -> ${targetUrl}`)
      callback({ redirectURL: targetUrl })
    } else {
      callback({ cancel: false })
    }
  })
}

// 关键：添加窗口调整的IPC监听（核心修改）
ipcMain.on('window-resize', (event, { width, height }) => {
  if (mainWindow) { // 确保窗口实例存在
    mainWindow.setSize(width, height, true); // 第三个参数true：平滑过渡
    mainWindow.center(); // 可选：调整后居中显示（体验更好）
  }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.whenReady().then(() => {
  electronApp.setAppUserModelId('com.electron')

  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // 原有IPC测试（保持不变）
  ipcMain.on('ping', () => console.log('pong'))

  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})
